package com.noble.glamour.module.logic.socket.stream;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.socket.NetData;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 读-写：数据流操作
 */
public class NetStream {

    /**
     * Socket登录信息数据包
     */
    public static NetData getLoginData() {
        Map<String, Object> loginMap = new HashMap<>();
        loginMap.put("Uid", ModuleMgr.getLoginMgr().getUid());
        loginMap.put("Auth", ModuleMgr.getLoginMgr().getAuth());
        return new NetData(JSON.toJSONString(loginMap));
    }

    /**
     * Socket心跳数据包:  空数据包
     */
    public static NetData getHeartbeat() {
        return new NetData();
    }

    /**
     * Socket消息回执数据包
     *
     * @param msgId 消息id：从消息头中获取
     * @return 回送消息体结构
     */
    public static NetData getLoopbackData(long msgId) {
        Map<String, Object> loopbackMap = new HashMap<>();
        loopbackMap.put("Id", msgId);
        loopbackMap.put("Uid", App.uid);
        return new NetData(JSON.toJSONString(loopbackMap));
    }

    /**
     * Socket传输消息体
     */
    public static byte[] getBytes(String msgBody) {
        byte[] ret = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (!TextUtils.isEmpty(msgBody.trim()))
                baos.write(msgBody.getBytes("UTF-8")); // 内容体写入流

            // 添加回车, 服务器做结束校验
            baos.write("\n".getBytes("UTF-8"));
            baos.flush();
            baos.close();
            ret = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError ooe) {
            ooe.printStackTrace();
        }
        return ret;
    }

    /**
     * 从数据流中解析并读取数据体
     */
    public static NetData parseNetData(InputStream inputStream) throws IOException {
        NetData netData;
        String msgBody;    // 接收到的消息体
        String line;

        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder buffer = new StringBuilder();

        try {
            // 服务器给的每条回复消息以回车符结尾，所以读到一条数据后直接break掉while循环
            while ((line = in.readLine()) != null) {
                buffer.append(line);
                break;
            }
            msgBody = buffer.toString();
        } finally {
//            in.close();
        }
        netData = new NetData(msgBody);
        return netData;
    }

}
